package demo.dcs.util;

import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.Base64;

/**
 * Created by dbwind.liu on 17/6/1.
 */
public class MacAddressUtil {

    public static String getFormateMacAddress(String macAddress) throws IOException {

        byte[] bt;
        if (StringUtils.isBlank(macAddress)) {
            return macAddress;
        }
        try {
            bt = Base64.getDecoder().decode(macAddress);
            String decodeAddress = bytes2HexString(bt);

            String formatMacAddress = formateMacAddress(decodeAddress);

            return formatMacAddress;
        } catch (Exception e) {
            throw e;
        }

    }

    public static String bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex;
        }
        return ret;
    }

    public static String formateMacAddress(String macAddress) {
        StringBuilder macFormatAddress = new StringBuilder();
        char[] macAddressArray = macAddress.toCharArray();
        for (int i = 0; i < macAddressArray.length; i++) {
            macFormatAddress.append(macAddressArray[i]);
            if (i % 2 == 1 && i < macAddressArray.length - 1) {
                macFormatAddress.append(":");
            }
        }

        return macFormatAddress.toString();
    }


}